//
//  BGColorViewController.swift
//  Swift2048
//
//  Created by LiynXu on 2016/9/27.
//  Copyright © 2016年 LiynXu. All rights reserved.
//

import UIKit


class BGColorViewController: UIViewController {
    
    var colorArray = [UIColor]()
    
    var collect:UICollectionView = {
        
        let layout:UICollectionViewFlowLayout  = {
            let layOut = UICollectionViewFlowLayout()
            layOut.itemSize = CGSize(width: 50, height: 50)
            layOut.scrollDirection = .Vertical
            layOut.minimumLineSpacing = 3
            layOut.minimumInteritemSpacing = 1
            return layOut
        }()
        
        let view = UICollectionView(frame: screenRect, collectionViewLayout: layout)
        view.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "CellID")
        view.backgroundColor = UIColor.blueColor()
        return view
    }()
    
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.collect.delegate = self
        self.collect.dataSource = self;
        self.view.addSubview(collect)
        
        
    }
    
}


extension BGColorViewController:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        
        return 1
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return COLOR.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CellID", forIndexPath: indexPath)
        
        let color = COLOR[indexPath.row]
        
        cell.backgroundColor = UIColor.init(red: color[0], green: color[1], blue: color[2], alpha: 1)
        
        
        return cell
        
    }
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
        let inset = UIEdgeInsets(top: 2, left: 2, bottom: 2, right: 2)
        return inset
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
       let navigationController = self.tabBarController?.childViewControllers[0] as! UINavigationController
        
        let viewController = navigationController.viewControllers[0]
        
        let color = COLOR[indexPath.row]
        
        NSUserDefaults.standardUserDefaults().setObject(color, forKey: "BGColor")
        viewController.view.backgroundColor = UIColor.init(red: color[0], green: color[1], blue: color[2], alpha: 1)
        
        self.tabBarController?.selectedIndex = 0
        
    }
    
    
}
